//
//  UITextView+Convenience.m
//  golfMaster
//
//  Created by MAC_XXK on 14-5-7.
//  Copyright (c) 2014年 宋鹏程. All rights reserved.
//

#import "UITextView+Convenience.h"

@implementation UITextView (Convenience)

- (void)addTarget:(id)target action:(SEL)action
{
    [self setUserInteractionEnabled:YES];
    UIControl *actionView = [[UIControl alloc] initWithFrame:self.bounds];
    actionView.backgroundColor = PCColorClear;
    [self addSubview:actionView];
    [self sendSubviewToBack:actionView];
    
    [actionView addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
}

- (CGFloat)measureHeight
{
    if ([self respondsToSelector:@selector(snapshotViewAfterScreenUpdates:)])
    {
        
        CGRect frame = self.bounds;
        
        UIEdgeInsets textContainerInsets = self.textContainerInset;
        UIEdgeInsets contentInsets = self.contentInset;
        
        CGFloat leftRightPadding = textContainerInsets.left + textContainerInsets.right + self.textContainer.lineFragmentPadding * 2 + contentInsets.left + contentInsets.right;
        CGFloat topBottomPadding = textContainerInsets.top + textContainerInsets.bottom + contentInsets.top + contentInsets.bottom;
        
        frame.size.width -= leftRightPadding;
        frame.size.height -= topBottomPadding;
        
        NSString *textToMeasure = self.text;
        if ([textToMeasure hasSuffix:@"\n"]){
            textToMeasure = [NSString stringWithFormat:@"%@-", self.text];
        }
        
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        [paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping];
        
        NSDictionary *attributes = @{ NSFontAttributeName: self.font, NSParagraphStyleAttributeName : paragraphStyle };
        
        //CGSize size = [textToMeasure sizeWithFont:self.font constrainedToSize:CGSizeMake(CGRectGetWidth(frame), MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
        
        CGRect size = [textToMeasure boundingRectWithSize:CGSizeMake(CGRectGetWidth(frame), MAXFLOAT)
                                                  options:NSStringDrawingUsesLineFragmentOrigin
                                               attributes:attributes
                                                  context:nil];
        
        //CGFloat measuredHeight = size.height + topBottomPadding;
        CGFloat measuredHeight = ceilf(CGRectGetHeight(size) + topBottomPadding);
        return measuredHeight ;
    }
    else
    {
        return self.contentSize.height;
    }
}

@end
